# -*- coding: UTF-8 -*-
import requests
import json
import time
import re
import cookielib

class PostWb:
    
    def __init__(self):
        self.session = requests.session()
        self.session.cookies=cookielib.LWPCookieJar()
        self.session.cookies.load("../cookies/logincookies", ignore_discard=True, ignore_expires=True)
        
    def postTextWb(self, text=""):
        if len(text) != 0:
            addurl = "http://weibo.com/aj/mblog/add?ajwvr=6&__" + str(int(time.time() * 100))
            data = {
                    'style_type': '1',
                    'text': text,
                    'rank':'0',
                    'location':'home',
                    'module':'stissue',
                    '_t':'0'
            }
            headers = {}
            headers['Referer'] = 'http://weibo.com/zziahui'
            r = self.session.post(addurl, data, headers=headers)
            rj = json.loads(r.text)
            if rj.get("code") == '100000':
                print "post text wb success！"
            else:
                print "post text wb fail"
    
    def postPicWb(self, img, text):
        uploadurl = "http://picupload.service.weibo.com/interface/pic_upload.php?app=miniblog&data=1&url=weibo.com/zziahui&markpos=1&logo=1&nick=%40zziahui&marks=1&url=weibo.com/zziahui&markpos=1&logo=1&nick=%40zziahui&marks=1&url=weibo.com/zziahui&markpos=1&logo=1&nick=%40zziahui&marks=1&mime=image/jpeg&ct=0.350373859051615"
        data = open(img, 'rb')
        r = self.session.post(uploadurl, data=data, headers={"Content-Type":"application/octet-stream"})
        result = re.sub(r"<meta.*</script>", "", r.text)
        image_result = json.loads(result)
        pid = image_result['data']['pics']['pic_1']['pid']
        addurl = "http://weibo.com/aj/mblog/add?ajwvr=6&__" + str(int(time.time() * 100))
        data = {
                'style_type': '1',
                'text':text,
                'rank':'0',
                'location':'v6_content_home',
                'module':'stissue',
                '_t':'0',
                "pub_source": "main_",
                "pub_type": "dialog",
                "rankid": "",
                "appkey": "",
                "pic_id": pid,
                "pdetail": "",
                "gif_ids": ""
        }
        headers = {}
        headers['Referer'] = 'http://weibo.com/zziahui?topnav=1&wvr=5'
        r = self.session.post(addurl, data, headers=headers)
        rj = json.loads(r.text)
        if rj.get("code") == '100000':
            print "post pic wb success！"
        else:
            print "post pic wb fail"

    def follow(self):
        pass    
    
postwb=PostWb()
postwb.search("大学")